package fr.curriculumvitae.anthony.stephan.activities;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Locale;

import fr.curriculumvitae.anthony.stephan.R;
import fr.curriculumvitae.anthony.stephan.SwipeyTabsActivity;
import fr.curriculumvitae.anthony.stephan.backend.BackEnd;
import fr.curriculumvitae.anthony.stephan.backend.IEditMessageCallback;
import fr.curriculumvitae.anthony.stephan.objects.Message;
import fr.curriculumvitae.anthony.stephan.pinnedsections.PinnedSectionListView;
import fr.curriculumvitae.anthony.stephan.pinnedsections.PinnedSectionListView.PinnedSectionListAdapter;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class AdminDashboardActivity extends ListActivity {
	
	private static final int REQUEST_READ = 1005;
	
	private static ListActivity mContext;
	
	private static List<Message> messages;
	
	@SuppressWarnings("unchecked")
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		// dismiss action bar
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		
		// get messages from extras
		Bundle extras = getIntent().getExtras();
		if(extras != null) {
			if(extras.get("messages") != null) {
				messages = (List<Message>) extras.getSerializable("messages");
			}
		} else {
			finish();
		}
		
		// set content view
		setContentView(R.layout.pinned_head_list);
		mContext = this;
		
		// initialize listview
		initializeListView();
		initializeAdapter();
		
		// adapt width & height (with max limits if needed)
        final ListView listView = (ListView) findViewById(android.R.id.list);
        ViewTreeObserver vto = listView.getViewTreeObserver(); 
        vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() { 
            @SuppressWarnings("deprecation")
			@Override 
            public void onGlobalLayout() { 
            	listView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                int layoutHeight = listView.getMeasuredHeight(); 
                
                DisplayMetrics metrics = getResources().getDisplayMetrics();
                int activityFinalWidth = (int) (metrics.widthPixels * 0.90);
                int activityFinalHeight = (int) (metrics.heightPixels * 0.75);
                if(layoutHeight<=activityFinalHeight) {
                	activityFinalHeight = layoutHeight;
                }
                getWindow().setLayout(activityFinalWidth, activityFinalHeight);
            } 
        });
	}
	
	private void initializeListView() {
		getListView().setPadding(0, 0, 0, 0);
		((PinnedSectionListView)getListView()).setShadowVisible(false);
	}

	private void initializeAdapter() {
		setListAdapter(new SimpleAdapter(this, android.R.layout.simple_list_item_1, android.R.id.text1));
	}
	
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {  
    	super.onActivityResult(requestCode, resultCode, data);
    	if(requestCode == REQUEST_READ) {
    		if(resultCode == Activity.RESULT_FIRST_USER && data != null && data.getExtras() != null) {
    			Message msg = (Message) data.getExtras().get(MessageDetailsActivity.EXTRA_MESSAGE);
    			if(msg != null) {
//    				if(SwipeyTabsActivity.mDialog != null) {
//    					SwipeyTabsActivity.mDialog.dismiss();
//    				}
//    				Context ctx = this;
//    				if(SwipeyTabsActivity.context != null) {
//    					ctx = SwipeyTabsActivity.context;
//    				}
//    				SwipeyTabsActivity.mDialog = ProgressDialog.show(ctx, 
//		    						getResources().getString(R.string.admin_update_message_dialog_title), 
//		    						getResources().getString(R.string.admin_update_message_dialog_message));
    				BackEnd.updateMessage(msg, true, editMessageCallback);
    			}
    		}
    	}
    }
	
	
	/////////////
	// ADAPTER //
	/////////////

	private static class SimpleAdapter extends ArrayAdapter<MessageItem> implements PinnedSectionListAdapter {

		public SimpleAdapter(Context context, int resource, int textViewResourceId) {
			super(context, resource, textViewResourceId);

			String sectionLabel = mContext.getResources().getString(R.string.admin_dashboard_section_label);
			prepareSections(1);

			MessageItem section = new MessageItem(MessageItem.SECTION, sectionLabel, null);
			section.sectionNumber = 0;
			section.sectionPosition = 0;
			onSectionAdded(section, 0);
			add(section);

			for(int j=0; j<messages.size(); j++) {
				MessageItem item = new MessageItem(MessageItem.ITEM, null, messages.get(j));
				item.sectionNumber = 0;
				item.sectionPosition = 0;
				add(item);
			}
		}

		protected void prepareSections(int sectionsNumber) {
			/* nothing to do */
		}

		protected void onSectionAdded(MessageItem section, int sectionPosition) { 
			/* nothing to do */
		}

		@Override 
		public View getView(int position, View convertView, ViewGroup parent) {
			LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			View view = null;
			MessageItem item = getItem(position);

			if(item.type == MessageItem.SECTION) {
				view = inflater.inflate(R.layout.layout_header, null);
				TextView tvSkillLavel = (TextView) view.findViewById(R.id.textView_skill_header_label);
				tvSkillLavel.setText(item.label);
				view.setBackgroundColor(parent.getResources().getColor(R.color.android_green_camaieu_1));
				view.setTag(null);

			} else if(item.type == MessageItem.ITEM) {
				view = inflater.inflate(R.layout.layout_row_message, null);
				ImageView ivMailIcon = (ImageView) view.findViewById(R.id.imageView_message_icon);
				TextView tvDate = (TextView) view.findViewById(R.id.textView_message_date);
				TextView tvEnterprise = (TextView) view.findViewById(R.id.textView_message_enterprise);
				if(item.msg.isRead()) {
					ivMailIcon.setImageDrawable(mContext.getResources().getDrawable(R.drawable.ic_email_read));
				} else {
					ivMailIcon.setImageDrawable(mContext.getResources().getDrawable(R.drawable.ic_email_not_read));
				}
				DateFormat dateFormat = new SimpleDateFormat("dd/MM/yy HH:mm", Locale.FRENCH);
				tvDate.setText(dateFormat.format(item.msg.getCreatedAt()));
				tvEnterprise.setText(item.msg.getEnterprise());
				view.setOnClickListener(new OnViewClickListener(item.msg));
			}

			return view;
		}

		@Override 
		public int getViewTypeCount() {
			return 2;
		}

		@Override 
		public int getItemViewType(int position) {
			return getItem(position).type;
		}

		@Override
		public boolean isItemViewTypePinned(int viewType) {
			return viewType == MessageItem.SECTION;
		}
	}


	@SuppressWarnings("unused")
	private static class MessageItem {
		public static final int ITEM = 0;
		public static final int SECTION = 1;
		public int sectionNumber;
		public int sectionPosition;
		public int listPosition;

		public final int type;
		public final String label;
		public final Message msg;

		public MessageItem(int type, String label, Message msg) {
			this.type = type;
			this.label = label;
			this.msg = msg;
		}
		@Override 
		public String toString() {
			return label;
		}
	}
	
	
	  ///////////////
	 // LISTENERS //
	///////////////
	
	private static class OnViewClickListener implements OnClickListener {
		private Message message;
		public OnViewClickListener(Message message) {
			this.message = message;
		}
		@Override
		public void onClick(View v) {
			Intent intent = new Intent(mContext, MessageDetailsActivity.class);
			intent.putExtra(MessageDetailsActivity.EXTRA_MESSAGE, message);
			mContext.startActivityForResult(intent, REQUEST_READ);
		}
	};
	
	
	  ///////////////
	 // CALLBACKS //
	///////////////
	
	private IEditMessageCallback editMessageCallback = new IEditMessageCallback() {
		@Override
		public void editMessageEnded(boolean success, String editedID, String message) {
//			if(SwipeyTabsActivity.mDialog != null) {
//				SwipeyTabsActivity.mDialog.dismiss();
//			}
			if(success) {
				for(Message m : messages) {
					if(m.getObjectId().equals(editedID)) {
						m.setRead(true);
						break;
					}
				}
				setListAdapter(new SimpleAdapter(mContext, android.R.layout.simple_list_item_1, android.R.id.text1));
				
			} else {
				if(SwipeyTabsActivity.mToast != null) {
					SwipeyTabsActivity.mToast.cancel();
				}
				SwipeyTabsActivity.mToast = Toast.makeText(mContext, getResources().getString(R.string.admin_update_message_dialog_error), Toast.LENGTH_LONG);
				SwipeyTabsActivity.mToast.show();
			}
		}
	};

}
